package com.hooview.web.template;

import com.hooview.utils.AjaxMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 执行模板
 *
 * @author gavincook
 * @version $Id: ExecuteTemplate.java, v0.1 2018-01-03 19:26 gavincook Exp $$
 */
@Component
public class ExecuteTemplate {

    /** 日志 */
    private final Logger LOGGER = LoggerFactory.getLogger(ExecuteTemplate.class);

    /**
     * 不带事务的模板
     *
     * @param callback
     * @param result
     */
    public void executeWithoutTransaction(ExecuteCallBack callback, AjaxMsg result) {
        doExecute(callback, result);
    }


    /**
     * 具体实现方法
     *
     * @param callback
     * @param result
     */
    private void doExecute(final ExecuteCallBack callback, final AjaxMsg result) {

        try {

            // 服务预检查
            callback.check();

            callback.service();

            // 构建成功结果
            buildResult(result, true, null);

        } catch (Exception e) {
            LOGGER.error("未知异常:{}", e.getMessage(), e);
            buildResult(result, false, e.getMessage());
        }
    }

    /**
     * 设置结果
     *
     * @param success
     */
    private void buildResult(AjaxMsg result, boolean success, String message) {
        result.setCode(success ? "200" : "500");
        result.setMessage(message);
    }
}